package cn.shiwei.basic.Interceptor;

import cn.shiwei.basic.util.RequestStatus;
import cn.shiwei.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 从请求体中拿到token
        String token = request.getHeader("token");
        System.out.println(token);
        // 从redis中取数据(token不为空情况下)
        if (!StringUtils.isEmpty(token)) {
            Object logininfo = redisTemplate.opsForValue().get(token);
            if (logininfo != null){
                System.out.println((Logininfo)logininfo);
                // 查出的信息不为空, 刷新redis中的过期事件
                redisTemplate.opsForValue().set(token, (Logininfo)logininfo, 30, TimeUnit.MINUTES);

                // 没问题放行
                return true;
            }
        }
        // 有问题, 不放行
        String requestStatus = RequestStatus.me().setMessage("登录失败, 请重新登录").toString();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // 将信息写给前端
        writer.write(requestStatus);
        writer.close();
        return false;
    }
}